package com.example.forjava.aspect;

import com.example.forjava.annotation.LogAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class LogInterceptor {

    /**
     * 定义用户管理模块的切点
     */
    @Pointcut("execution(* com.example.forjava.controller..*.aopCustom(..))")
    public void userManagerPointcut(){
    }

    @After("userManagerPointcut()")
    public void afterLog(JoinPoint joinPoint) throws NoSuchMethodException {
        //用的最多通知的签名
        Signature signature = joinPoint.getSignature();
        MethodSignature msg=(MethodSignature) signature;
        Object target = joinPoint.getTarget();
        //获取注解标注的方法
        Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
        //通过方法获取到自定义的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);

        //记录日志
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date())
                + "  " + annotation.moduleName() + "  " + annotation.option());

    }
}